package com.lxk.util.exception;

import com.lxk.vo.result.CodeMsg;
import com.lxk.vo.result.Result;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * @author JohnSoybean
 * @create 2020/3/19 16:06
 * @description 全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value=Exception.class)
    public Object exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();    //开发阶段开启
        if(e instanceof GlobalException) {
            GlobalException ex = (GlobalException)e;
            return Result.error(ex.getCm());
        }else if(e instanceof BindException) {
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else if(e instanceof ConstraintViolationException) {
            String msg = e.getMessage();
            msg = msg.substring(msg.indexOf(" ") + 1);
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else if(e instanceof NullPointerException) {
            return Result.error(CodeMsg.NULL_POINTER);
        }else if(e instanceof NoHandlerFoundException){
            return Result.error(CodeMsg.NO_HANDLER_FOUND);
        }else if(e instanceof RedisConnectionFailureException){
            return Result.error(CodeMsg.REDIS_CONNECT_ERR);
        }else {
            //单独参数的校验异常
            if (e.getClass().equals(ConstraintViolationException.class)) {
                String msg = e.getMessage();
                msg = msg.substring(msg.indexOf(" ")+1);
                return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
            }
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

}
